package me.youline.dataServer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import me.youline.dataServer.entity.UserSocialRelation;
import me.youline.dataServer.utils.IdPageSqlHelper;
import me.youline.dataServer.utils.IdPagination;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class UserSocialRelationDAO {

	private static final String FOLLOWER_TABLE_NAME = "yline_social_followers";

	private static final String FOLLOW_TABLE_NAME = "yline_social_follows";

	private static final String QUERY_USER_FOLLOWERS_SQL = "select * from "
			+ FOLLOWER_TABLE_NAME
			+ " where %s and toUserId = ? order by id desc %s";

	private static final String QUERY_USER_FOLLOWS_SQL = "select * from "
			+ FOLLOW_TABLE_NAME
			+ " where %s and fromUserId = ? order by id desc %s ";

	private static final String INSERT_FOLLOWER_SQL = "insert into "
			+ FOLLOWER_TABLE_NAME + " (fromUserId,toUserId) values(?,?)";

	private static final String INSERT_FOLLOW_SQL = "insert into "
			+ FOLLOW_TABLE_NAME + "(fromUserId,toUserId) values(?,?)";

	private static final String DELETE_FOLLOWER_SQL = "delete from "
			+ FOLLOWER_TABLE_NAME + " where fromUserId = ? and toUserId = ?";

	private static final String DELETE_FOLLOW_SQL = "delete from "
			+ FOLLOW_TABLE_NAME + " where fromUserId = ? and toUserId = ?";

	private static final String COUNT_FOLLOWER_SQL = "select count(1) from "
			+ FOLLOWER_TABLE_NAME + " where toUserId = ?";

	private static final String COUNT_FOLLOW_SQL = "select count(1) from "
			+ FOLLOW_TABLE_NAME + " where fromUserId = ?";

	private static final String COUNT_FOLLOWER_REL_EXIST_SQL = "select count(1) from "
			+ FOLLOWER_TABLE_NAME + " where  toUserId = ? and fromUserId = ? ";

	private static final RowMapper<UserSocialRelation> ROW_MAPPER = new RowMapper<UserSocialRelation>() {

		@Override
		public UserSocialRelation mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			UserSocialRelation rel = new UserSocialRelation();
			rel.setCreateTime(rs.getDate("createTime"));
			rel.setFromUserId(rs.getLong("fromuserId"));
			rel.setId(rs.getLong("id"));
			rel.setToUserId(rs.getLong("toUserId"));
			return rel;
		}
	};

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 添加用户社交关系
	 * 
	 * @param fromUserId
	 *            发起关注人
	 * @param toUserId
	 *            被关注人
	 */
	@Transactional
	public void addUserRelation(Long fromUserId, Long toUserId) {
		jdbcTemplate.update(INSERT_FOLLOW_SQL, new Object[] { fromUserId,
				toUserId });
		jdbcTemplate.update(INSERT_FOLLOWER_SQL, new Object[] { fromUserId,
				toUserId });
	}

	/**
	 * 分页获取用户的粉丝列表
	 * 
	 * @param userId
	 * @param page
	 * @return
	 */
	public List<UserSocialRelation> getFollowersByUserRels(Long userId,
			IdPagination page) {
		IdPageSqlHelper helper = IdPageSqlHelper.create(page);
		String sql = String.format(QUERY_USER_FOLLOWERS_SQL,
				helper.getPagingSqlCondition(), helper.getSizeSqlCondition());
		Object[] data = null;
		if (helper.getIds().length == 0) {
			data = new Object[] { userId };
		} else if (helper.getIds().length == 1) {
			data = new Object[] { helper.getIds()[0], userId};
		} else if (helper.getIds().length == 2) {
			data = new Object[] { helper.getIds()[0], helper.getIds()[1],
					userId };
		}
		List<UserSocialRelation> list = jdbcTemplate.query(sql, data,
				ROW_MAPPER);
		if (list == null) {
			return Collections.emptyList();
		}
		return list;
	}

	/**
	 * 分页获取用户的关注列表
	 * 
	 * @param userId
	 * @param page
	 * @return
	 */
	public List<UserSocialRelation> getUserFollowingRels(Long userId,
			IdPagination page) {
		IdPageSqlHelper helper = IdPageSqlHelper.create(page);
		String sql = String.format(QUERY_USER_FOLLOWS_SQL,
				helper.getPagingSqlCondition(), helper.getSizeSqlCondition());
		Object[] data = null;
		if (helper.getIds().length == 0) {
			data = new Object[] { userId };
		} else if (helper.getIds().length == 1) {
			data = new Object[] { helper.getIds()[0], userId };
		} else if (helper.getIds().length == 2) {
			data = new Object[] { helper.getIds()[0], helper.getIds()[1],
					userId };
		}
		List<UserSocialRelation> list = jdbcTemplate.query(sql, data,
				ROW_MAPPER);
		if (list == null) {
			return Collections.emptyList();
		}
		return list;
	}

	/**
	 * 删除用户社交关系
	 * 
	 * @param fromUserId
	 *            发起关注者
	 * @param toUserId
	 *            被关注人
	 */
	@Transactional
	public boolean deleteUserRelation(Long fromUserId, Long toUserId) {
		int r= jdbcTemplate.update(DELETE_FOLLOWER_SQL, new Object[] { fromUserId,
				toUserId });
		int m = jdbcTemplate.update(DELETE_FOLLOW_SQL, new Object[] { fromUserId,
				toUserId });
		return r>0 && m >0;
	}

	/**
	 * 统计用户的粉丝数
	 * 
	 * @param userId
	 * @return
	 */
	public int countUserFollowerNum(Long userId) {
		return jdbcTemplate.queryForObject(COUNT_FOLLOWER_SQL, Integer.class,
				new Object[] { userId });
	}

	/**
	 * 统计用户的关注数
	 * 
	 * @param userId
	 * @return
	 */
	public int countUserFollowNum(Long userId) {
		return jdbcTemplate.queryForObject(COUNT_FOLLOW_SQL, Integer.class,
				new Object[] { userId });
	}

	/**
	 * 查询用户是否为指定用户的粉丝（是否已经关注指定用户）
	 * 
	 * @param userId
	 * @param targetUserId
	 * @return
	 */
	public boolean isFollowerToTargetUser(Long userId, Long targetUserId) {
		int res = jdbcTemplate.queryForObject(COUNT_FOLLOWER_REL_EXIST_SQL,
				new Object[] { targetUserId, userId }, Integer.class);
		return res == 1;
	}

}
